<template>
  <el-container class="document-editor-container">
    <el-aside width="250px" class="control-panel-wrapper">
      <ControlPanel @drag-start="handleDragStart" />
    </el-aside>

    <el-main class="pdf-editor-wrapper">
      <PDFEditor
        :pdf-url="currentPdfUrl"
        :placed-controls="placedControls"
        :selected-control="selectedControl"
        @control-dropped="handleControlDropped"
        @control-selected="handleControlSelected"
        @control-updated="handleControlUpdated"
        @control-resized="handleControlResized"
        @control-moved="handleControlMoved"
      />
    </el-main>
    <el-aside width="250px" class="properties-panel-wrapper">
      <PropertiesPanel
        :selected-control="selectedControl"
        @update-control-properties="updateControlProperties"
      />
      <div class="actions-panel">
        <el-button type="primary" @click="saveDocument">保存文档配置</el-button>
        <el-button @click="loadDocument">从本地存储加载</el-button>
        <el-button @click="loadDocument(true)">从文件导入</el-button>
      </div>
    </el-aside>
  </el-container>

  <el-dialog
    v-model="showSignatureDialog"
    title="在线签名"
    width="600px"
    :close-on-click-modal="false"
    @closed="resetSignaturePad"
  >
    <SignaturePad @signed="handleGlobalSignature" @clear="showSignatureDialog = false" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showSignatureDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmGlobalSignature">确认签名</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
// 这里直接复制原App.vue的<script setup>内容
import { ref, reactive, onMounted } from 'vue';
import ControlPanel from './ControlPanel.vue';
import PDFEditor from './PDFEditor.vue';
import PropertiesPanel from './PropertiesPanel.vue';
import SignaturePad from './SignaturePad.vue';
import { ElMessage } from 'element-plus';

const currentPdfUrl = ref('sample.pdf');
const placedControls = reactive([]);
const selectedControl = ref(null);
const showSignatureDialog = ref(false);
let latestSignatureData = null;

const handleDragStart = (type) => {
  window.draggingControlType = type;
};
const handleControlDropped = (controlData) => {
  const newControl = {
    id: controlData.id,
    type: controlData.type,
    typeName: controlData.typeName,
    page: controlData.page,
    x: controlData.x,
    y: controlData.y,
    width: controlData.width,
    height: controlData.height,
    coordinateRatio: controlData.coordinateRatio,
    properties: {
      label: controlData.typeName || `${controlData.type}字段`,
      placeholder: controlData.properties?.placeholder || '',
      required: false,
      defaultValue: '',
    },
    value: null,
  };
  if (controlData.type === 'textarea') {
    newControl.properties.rows = 3;
  } else if (controlData.type === 'select') {
    newControl.properties.options = [
      { label: '选项1', value: '1' },
      { label: '选项2', value: '2' },
      { label: '选项3', value: '3' }
    ];
  } else if (controlData.type === 'radio') {
    newControl.properties.options = [
      { label: '选项1', value: '1' },
      { label: '选项2', value: '2' },
      { label: '选项3', value: '3' }
    ];
  } else if (controlData.type === 'checkbox') {
    newControl.properties.checked = false;
  } else if (controlData.type === 'checkbox-group') {
    newControl.properties.options = [
      { label: '选项1', value: '1' },
      { label: '选项2', value: '2' },
      { label: '选项3', value: '3' }
    ];
  } else if (controlData.type === 'signature') {
    newControl.properties.signatureType = 'draw';
  }
  placedControls.push(newControl);
  selectedControl.value = newControl;
  window.draggingControlType = null;
  ElMessage.success(`已放置 ${newControl.properties.label}`);
};
const handleControlSelected = (controlId) => {
  selectedControl.value = controlId ? placedControls.find(c => c.id === controlId) : null;
};
const updateControlProperties = (updatedProps) => {
  if (selectedControl.value) {
    Object.assign(selectedControl.value.properties, updatedProps);
  }
};
const handleControlUpdated = (controlId, key, value) => {
  const control = placedControls.find(c => c.id === controlId);
  if (control) {
    control.properties[key] = value;
  }
};
const handleControlResized = (controlId, newWidth, newHeight) => {
  const control = placedControls.find(c => c.id === controlId);
  if (control) {
    control.width = newWidth;
    control.height = newHeight;
  }
};
const handleControlMoved = (controlId, newX, newY, newPage) => {
  const control = placedControls.find(c => c.id === controlId);
  if (control) {
    const oldPage = control.page;
    control.x = newX;
    control.y = newY;
    control.page = newPage;
    if (oldPage !== newPage) {
      ElMessage.info(`控件移动到页面${newPage}`);
    }
  }
};
const handleGlobalSignature = (signatureBase64) => {
  latestSignatureData = signatureBase64;
  ElMessage.success('签名已捕获，请确认！');
};
const confirmGlobalSignature = () => {
  if (latestSignatureData && selectedControl.value && selectedControl.value.type === 'signature') {
    selectedControl.value.value = latestSignatureData;
    ElMessage.success('签名已应用到控件！');
  } else {
    ElMessage.warning('没有捕获到签名或未选择签名控件！');
  }
  showSignatureDialog.value = false;
  latestSignatureData = null;
};
const resetSignaturePad = () => {
  latestSignatureData = null;
};
const saveDocument = () => {
  try {
    const pdfInfo = window.pdfInfo || {};
    const controlsToSave = JSON.parse(JSON.stringify(placedControls));
    const documentData = {
      pdfUrl: currentPdfUrl.value,
      controls: controlsToSave,
      pdfInfo: pdfInfo,
      version: '1.0',
      createdAt: new Date().toISOString(),
    };
    localStorage.setItem('savedDocument', JSON.stringify(documentData));
    const jsonData = JSON.stringify(documentData, null, 2);
    const blob = new Blob([jsonData], { type: 'application/json' });
    const fileName = `form_config_${new Date().toISOString().slice(0, 10)}.json`;
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    ElMessage.success('文档配置已保存！');
  } catch (error) {
    console.error('保存文档配置失败:', error);
    ElMessage.error('保存文档配置失败!');
  }
};
const loadDocument = (fromFile = false) => {
  try {
    let documentData;
    if (fromFile) {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.json';
      input.onchange = (event) => {
        const file = event.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e) => {
            try {
              const jsonData = e.target.result;
              documentData = JSON.parse(jsonData);
              applyDocumentData(documentData);
            } catch (error) {
              console.error('读取JSON文件失败:', error);
              ElMessage.error('文件格式错误，无法加载文档配置!');
            }
          };
          reader.readAsText(file);
        }
      };
      input.click();
    } else {
      const savedData = localStorage.getItem('savedDocument');
      if (savedData) {
        documentData = JSON.parse(savedData);
        applyDocumentData(documentData);
      } else {
        ElMessage.info('没有找到已保存的文档配置。');
      }
    }
  } catch (error) {
    console.error('加载文档配置失败:', error);
    ElMessage.error('加载文档配置失败!');
  }
};
const applyDocumentData = (documentData) => {
  if (!documentData || !documentData.controls) {
    ElMessage.error('文档配置数据无效!');
    return;
  }
  currentPdfUrl.value = documentData.pdfUrl;
  if (documentData.pdfInfo) {
    window.pdfInfo = documentData.pdfInfo;
  }
  placedControls.splice(0, placedControls.length);
  setTimeout(() => {
    documentData.controls.forEach(control => {
      placedControls.push(control);
    });
    selectedControl.value = null;
    ElMessage.success('文档配置已加载！');
  }, 1000);
};
onMounted(() => {
  return () => {
    window.draggingControlType = null;
  };
});
</script>

<style scoped>
.document-editor-container {
  height: 95vh;
  overflow: hidden;
  display: flex;
}
.control-panel-wrapper {
  padding: 20px;
  background-color: #f5f7fa;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  box-sizing: border-box;
  flex-shrink: 0;
}
.pdf-editor-wrapper {
  flex: 1;
  overflow: hidden;
  box-sizing: border-box;
  background-color: #f0f2f5;
}
.thumbnail-panel {
  background: #fff;
  border-left: 1px solid #ebeef5;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
}
.properties-panel-wrapper {
  padding: 20px;
  background-color: #f5f7fa;
  border-left: 1px solid #ebeef5;
  overflow-y: auto;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.actions-panel {
  margin-top: auto;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 